<template>
	<!-- 宽带账号 -->
	<el-row :gutter="20">
		<!-- 左侧部门树 -->
		<el-col :span="4" :xs="24">
			<ContentWrap class="h-1/1">
				<CommunityTree @node-click="handleCommunityNodeClick" />
			</ContentWrap>
		</el-col>
		<el-col :span="20" :xs="24">
			<ContentWrap>
				<!-- 搜索工作栏 -->
				<el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
					<el-form-item label="中间件" prop="netSysId">
						<el-select v-model="queryParams.netSysId" placeholder="中间件" class="!w-260px" clearable>
							<el-option v-for="n in sysConfigList" :key="n.id" :label="n.community.name" :value="n.id" />
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-input v-model="queryParams.packName" placeholder="请输入关键字" clearable @keyup.enter.stop="handleQuery">
							<template #prepend>
								<el-select v-model="kType" placeholder="请选择" class="!w-120px">
									<el-option label="账号" value="netAccount" />
									<el-option label="地址" value="netAddress" />
									<el-option label="手机号" value="phone" />
								</el-select>
							</template>
						</el-input>
					</el-form-item>
					<el-form-item>
						<el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" />搜索</el-button>
						<el-button type="primary" plain v-hasPermi="['zwsj:net-account:create']" @click="openCreate"><Icon icon="ep:plus" class="mr-5px" />新增 </el-button>
					</el-form-item>
				</el-form>
			</ContentWrap>
			<ContentWrap>
				<el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
					<el-table-column label="序号" align="left" width="55">
						<template #default="scope">
							<div>{{ scope.row.id }}</div>
						</template>
					</el-table-column>
					<el-table-column label="社区/中间件" align="left" width="160">
						<template #default="scope">
							<div>社区：{{ scope.row.community.name }}</div>
							<template v-for="item in sysConfigList">
								<div :key="item.id" v-if="item.id == scope.row.netSysId">中间件：{{ item.community.name }}</div>
							</template>
						</template>
					</el-table-column>
					<el-table-column label="宽带账号/套餐名称" align="left">
						<template #default="scope">
							<div>宽带账号：{{ scope.row.netAccount }}</div>
							<div>套餐名称：{{ scope.row.packageDO.packName }}</div>
						</template>
					</el-table-column>
					<el-table-column label="地址" align="left" width="360">
						<template #default="scope">
							<div>{{ scope.row.netAddress }}</div>
						</template>
					</el-table-column>
					<el-table-column label="创建时间/过期时间/最后一次充值时间" align="left">
						<template #default="scope">
							<div>创建时间：{{ formatDate(scope.row.createTime) }}</div>
							<div>过期时间：{{ formatDate(scope.row.newNetExpiresTime) }}</div>
							<div>最后一次充值时间：{{ formatDate(scope.row.lastPayTime) }}</div>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" fixed="right" width="180">
						<template #default="scope">
							<el-button link type="primary" @click="change0pen(scope.row)" v-hasPermi="['zwsj:net-account:update']">子账号</el-button>
							<el-button link type="primary" @click="openForm(scope.row)" v-hasPermi="['zwsj:net-account:update']">编辑</el-button>
							<el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['zwsj:net-account:delete']">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页 -->
				<Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="getList" />
			</ContentWrap>
		</el-col>
	</el-row>

	<!-- 新增 -->
	<el-dialog v-model="dialogVisibleCreate" title="新增" width="40%">
		<el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
			<el-tab-pane label="通过租住信息创建" name="rent">
				<el-form ref="formRef1" :model="createFormData" :rules="formRules" label-width="120px" v-loading="formLoading">
					<el-form-item label="宽带账号" prop="netAccount">
						<el-input v-model="createFormData.netAccount" placeholder="宽带账号" />
					</el-form-item>
					<el-form-item label="套餐" prop="netPackageId">
						<el-select v-model="createFormData.netPackageId" filterable remote placeholder="请选择相关套餐" :remote-method="remoteCreateList">
							<el-option v-for="item in pageLisrt" :key="item.id" :label="item.packName" :value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="租住关系" prop="relaId" style="width: 100%; display: flex; align-items: center">
						<div style="width: 100%; display: flex; align-items: center">
							<el-select v-model="createkType" placeholder="请选择" class="!w-160px">
								<el-option label="租客姓名" value="name" />
								<el-option label="租住地址" value="address" />
							</el-select>
							<el-select v-model="createFormData.relaId" filterable remote placeholder="请选择租住关系" :remote-method="remoteCreateRent">
								<el-option v-for="item in rentList" :key="item.id" :label="item.rentAddrName + `（${item.rentUserName}）`" :value="item.id" />
							</el-select>
						</div>
					</el-form-item>
				</el-form>
				<div class="dialog-footer" style="text-align: right">
					<el-button @click="dialogVisibleCreate = false">取消</el-button>
					<el-button type="primary" @click="submitCreate1"> 确定 </el-button>
				</div>
			</el-tab-pane>
			<el-tab-pane label="通过用户信息创建" name="second">
				<el-form ref="formRef2" :model="createFormData" :rules="formRules" label-width="120px" v-loading="formLoading">
					<el-form-item label="宽带账号" prop="netAccount">
						<el-input v-model="createFormData.netAccount" placeholder="宽带账号" />
					</el-form-item>
					<el-form-item label="用户" prop="memberUserId" style="width: 100%; display: flex; align-items: center">
						<div style="width: 100%; display: flex; align-items: center">
							<el-select v-model="createkUserType" placeholder="请选择" class="!w-160px">
								<el-option label="手机号" value="mobile" />
								<el-option label="用户昵称" value="nickname" />
							</el-select>
							<el-select v-model="createFormData.memberUserId" filterable remote placeholder="请输入用户名称" :remote-method="remoteCreateUser">
								<el-option v-for="item in userList" :key="item.id" :label="`${item.nickname}` + `（${item.name}）`" :value="item.id" />
							</el-select>
						</div>
					</el-form-item>
					<el-form-item label="套餐" prop="netPackageId">
						<el-select v-model="createFormData.netPackageId" filterable remote placeholder="请选择相关套餐" :remote-method="remoteCreateList">
							<el-option v-for="item in pageLisrt" :key="item.id" :label="item.packName" :value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="房产" prop="houseId">
						<el-select v-model="createFormData.houseId" filterable remote placeholder="请选择房产" :remote-method="remoteCreateHouse">
							<el-option v-for="item in houseList" :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="房间" prop="roomId">
						<el-select v-model="createFormData.roomId" filterable remote placeholder="请选择房间" :remote-method="remoteCreateRoom">
							<el-option v-for="item in roomList" :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-form>
				<div class="dialog-footer" style="text-align: right">
					<el-button @click="dialogVisibleCreate = false">取消</el-button>
					<el-button type="primary" @click="submitCreate2"> 确定 </el-button>
				</div>
			</el-tab-pane>
		</el-tabs>
	</el-dialog>

	<!-- 编辑 -->
	<el-dialog v-model="dialogVisibleEdit" title="编辑" width="30%">
		<el-form :model="formData" label-width="120px" v-loading="formLoading">
			<el-form-item label="套餐" prop="bindPackId">
				<el-select v-model="formData.groupId" filterable remote placeholder="请选择相关套餐" :remote-method="remoteList">
					<el-option v-for="item in pageLisrt" :key="item.id" :label="item.packName" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="过期时间">
				<el-date-picker
					:clearable="false"
					style="width: 100%"
					v-model="formData.newNetExpiresTime"
					type="datetime"
					placeholder="过期时间"
					:default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
					@change="handleDateChange" />
			</el-form-item>
			<el-form-item label="房产" prop="houseId">
				<el-select v-model="formData.houseId" filterable remote placeholder="请选择房产" :remote-method="remoteHouse">
					<el-option v-for="item in houseList" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="房间" prop="roomId">
				<el-select v-model="formData.roomId" filterable remote placeholder="请选择房间" :remote-method="remoteRoom">
					<el-option v-for="item in roomList" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogVisibleEdit = false">取消</el-button>
				<el-button type="primary" @click="submitForm"> 确定 </el-button>
			</div>
		</template>
	</el-dialog>

	<!-- 子账号 -->
	<el-dialog v-model="subAccountShow" title="子账号列表" width="60%">
		<el-table :data="subAccountList" :height="600" :stripe="true" border :show-overflow-tooltip="true">
			<el-table-column label="序号" align="center" width="80">
				<template #default="scope">{{ scope.row.id }}</template>
			</el-table-column>
			<el-table-column label="账号" align="center">
				<template #default="scope">{{ scope.row.netAccount }}</template>
			</el-table-column>
			<el-table-column label="地址" align="center">
				<template #default="scope">{{ scope.row.netAddress }}</template>
			</el-table-column>
			<el-table-column label="过期时间" align="center">
				<template #default="scope">{{ formatDate(scope.row.newNetExpiresTime) }}</template>
			</el-table-column>
		</el-table>
	</el-dialog>
</template>
<script setup lang="ts">
	import CommunityTree from '@/views/zwsj/common/CommunityTree.vue'
	import { getNetSysConfigs } from '@/api/zwsj/netSysConfig'
	import * as NetAccountApi from '@/api/zwsj/netAccount'
	import * as NetPackageApi from '@/api/zwsj/netPackage'
	import { formatDate } from '@/utils/formatTime'
	import * as houseRoom from '@/api/zwsj/houseRoom'
	import type { TabsPaneContext } from 'element-plus'
	import * as RoomRentApi from '@/api/zwsj/roomRent'
	import * as UserApi from '@/api/member/user'

	const message = useMessage() // 消息弹窗
	const loading = ref(true) // 列表的加载中
	const { t } = useI18n() // 国际化
	const total = ref(0) // 列表的总页数
	const list = ref([]) // 列表的数据
	const sysConfigList = ref([])
	const kType = ref('netAccount')
	const queryParams = reactive({
		pageNo: 1,
		commId: null,
		pageSize: 10,
		netSysId: null, // 中间件
		netAddress: null, // 地址
		netAccount: null, // 账号
		packName: null, // 关键字
		mobile: null, // 手机号
	})

	const dialogVisibleEdit = ref(false)
	const dialogVisibleCreate = ref(false)
	const subAccountShow = ref(false)
	const formData = ref()
	const createFormData = reactive({
		netAccount: '', // 宽带账号
		netPackageId: '', // 套餐id
		relaId: '', // 租住关系id
		memberUserId: '', // 用户id
		houseId: '', // 房产id
		roomId: '', // 房间id
	})
	const formRules = reactive({
		netAccount: [{ required: true, message: '宽带账号不能为空', trigger: 'blur' }],
		netPackageId: [{ required: true, message: '套餐不能为空', trigger: 'blur' }],
		relaId: [{ required: true, message: '租住关系不能为空', trigger: 'blur' }],
		memberUserId: [{ required: true, message: '用户不能为空', trigger: 'blur' }],
		houseId: [{ required: true, message: '房产不能为空', trigger: 'blur' }],
		roomId: [{ required: true, message: '房间不能为空', trigger: 'blur' }],
	})
	const formRef1 = ref() // 表单 Ref
	const formRef2 = ref()
	const activeName = ref('rent')
	const createkType = ref('name')
	const createkUserType = ref('mobile')
	const formLoading = ref(false)
	const pageLisrt = ref([])
	const houseList = ref([])
	const roomList = ref([])
	const rentList = ref([])
	const userList = ref([])

	/** 处理区域被点击 */
	const handleCommunityNodeClick = async row => {
		queryParams.commId = row.id
		await getList()
	}

	/** 查询列表 */
	const getList = async () => {
		loading.value = true
		try {
			const data = await NetAccountApi.getPage(queryParams)
			list.value = data.list
			total.value = data.total
		} finally {
			loading.value = false
		}
	}

	/** 搜索按钮操作 */
	const handleQuery = () => {
		queryParams.netAddress = null // 地址
		queryParams.netAccount = null //  账号
		queryParams.mobile = null // 手机号
		if (kType.value == 'netAddress') {
			queryParams.netAddress = queryParams.packName // 地址
		} else if (kType.value == 'netAccount') {
			queryParams.netAccount = queryParams.packName //  账号
		} else if (kType.value == 'phone') {
			queryParams.mobile = queryParams.packName // 手机号
		}
		queryParams.pageNo = 1
		getList()
	}

	const openForm = async (item: object) => {
		pageLisrt.value = []
		houseList.value = []
		roomList.value = []
		if (item.packageDO) {
			pageLisrt.value.push(item.packageDO)
		}
		if (item.houseDO) {
			houseList.value.push(item.houseDO)
		}
		if (item.roomDO) {
			roomList.value.push(item.roomDO)
		}
		formData.value = item
		dialogVisibleEdit.value = true
	}

	// 搜索套餐
	const remoteList = async (query: string) => {
		try {
			if (query) {
				const params = {
					pageNo: 1,
					commId: formData.value.commId,
					pageSize: 100,
					netSysId: formData.value.netSysId,
					packName: query,
				}
				const data = await NetPackageApi.getPage(params)
				pageLisrt.value = data.list || []
			}
		} catch (error) {}
	}

	// 搜索房产
	const remoteHouse = async (query: string) => {
		try {
			if (query) {
				if (!formData.value.commId) {
					message.error('请先选择社区')
					return
				}
				houseList.value = []
				const data = {
					commId: formData.value.commId,
					keyWord: query,
					pageNo: 1,
					pageSize: 100,
					parentId: 0,
				}
				const res = await houseRoom.getHouseRoomPage(data)
				houseList.value = res.list || []
				return
			}
		} finally {
		}
	}

	// 搜索房屋
	const remoteRoom = async (query: string) => {
		try {
			if (query) {
				if (!formData.value.commId) {
					message.error('请先选择社区')
					return
				}
				if (!formData.value.houseId) {
					message.error('请先选择房产')
					return
				}
				roomList.value = []
				const data = {
					keyWord: query,
					pageNo: 1,
					pageSize: 100,
					commId: formData.value.commId,
					parentId: formData.value.houseId,
				}
				const res = await houseRoom.getHouseRoomPage(data)
				roomList.value = res.list || []
				return
			}
		} finally {
		}
	}

	// 处理日期变更
	const handleDateChange = val => {
		if (val) {
			// 将选择的日期时间转换为时间戳
			formData.value.newNetExpiresTime = new Date(val).getTime()
		} else {
			formData.value.newNetExpiresTime = null
		}
	}

	const submitForm = async () => {
		if (formData.value.groupId) {
			const index = pageLisrt.value.findIndex(item => item.id == formData.value.groupId)
			if (index != -1) {
				const item = pageLisrt.value[index]
				formData.value.groupId = item.id
				formData.value.packageId = item.lfPackId
			}
		} else {
			message.error('请选择套餐')
			return
		}

		// 提交请求
		formLoading.value = true
		try {
			const data = formData.value as unknown as NetAccountApi.NetAccountVO
			await NetAccountApi.updatePackage(data)
			message.success(t('common.success'))
			dialogVisibleEdit.value = false
			getList()
		} finally {
			formLoading.value = false
		}
	}

	// 新增弹窗
	const openCreate = async () => {
		initData()
		dialogVisibleCreate.value = true
	}

	// 初始化数据
	const initData = async () => {
		createFormData.netAccount = '' // 宽带账号
		createFormData.netPackageId = '' // 套餐id
		createFormData.relaId = '' // 租住关系id
		createFormData.memberUserId = '' // 用户id
		createFormData.houseId = '' // 房产id
		createFormData.roomId = '' // 房间id
		pageLisrt.value = []
		houseList.value = []
		roomList.value = []
		rentList.value = []
		userList.value = []
		formRef1.value?.resetFields()
		formRef2.value?.resetFields()
	}

	// 切换新增弹窗菜单
	const handleClick = (tab: TabsPaneContext) => {
		initData()
		activeName.value = tab.paneName
	}

	// 搜索租住关系
	const remoteCreateRent = async (query: string) => {
		try {
			if (query) {
				rentList.value = []
				const data = {
					pageNo: 1,
					pageSize: 100,
					commId: queryParams.commId,
					rentAddrName: null,
					rentUserName: null,
				}
				if (createkType.value == 'name') {
					data.rentUserName = query
				} else {
					data.rentAddrName = query
				}
				const res = await RoomRentApi.getRoomRentPage(data)
				rentList.value = res.list || []
				return
			}
		} finally {
		}
	}

	// 搜索用户
	const remoteCreateUser = async (query: string) => {
		try {
			if (query) {
				userList.value = []
				const data = {
					pageNo: 1,
					pageSize: 100,
					nickname: null,
					mobile: null,
				}
				if (createkUserType.value == 'mobile') {
					data.mobile = query
				} else {
					data.nickname = query
				}
				const res = await UserApi.getUserPage(data)
				userList.value = res.list || []
				return
			}
		} finally {
		}
	}

	// 搜索套餐
	const remoteCreateList = async (query: string) => {
		try {
			if (query) {
				const params = {
					pageNo: 1,
					commId: queryParams.commId,
					pageSize: 100,
					netSysId: queryParams.netSysId,
					packName: query,
				}
				const data = await NetPackageApi.getPage(params)
				pageLisrt.value = data.list || []
			}
		} catch (error) {}
	}

	// 搜索房产
	const remoteCreateHouse = async (query: string) => {
		try {
			if (query) {
				houseList.value = []
				const data = {
					commId: queryParams.commId,
					keyWord: query,
					pageNo: 1,
					pageSize: 100,
					parentId: 0,
				}
				const res = await houseRoom.getHouseRoomPage(data)
				houseList.value = res.list || []
				return
			}
		} catch (error) {}
	}

	// 搜索房屋
	const remoteCreateRoom = async (query: string) => {
		try {
			if (query) {
				if (!createFormData.houseId) {
					message.error('请先选择房产')
					return
				}
				roomList.value = []
				const data = {
					keyWord: query,
					pageNo: 1,
					pageSize: 100,
					commId: queryParams.commId,
					parentId: createFormData.houseId,
				}
				const res = await houseRoom.getHouseRoomPage(data)
				roomList.value = res.list || []
				return
			}
		} catch (error) {}
	}

	// 创建宽带账号(通过租住信息创建)
	const submitCreate1 = async () => {
		// 校验表单
		if (!formRef1) return
		const valid = await formRef1.value.validate()
		if (!valid) return
		formLoading.value = true
		try {
			const data = createFormData as unknown as NetAccountApi.NetAccountCreateVO
			await NetAccountApi.createRent(data)
			message.success(t('common.success'))
			dialogVisibleCreate.value = false
			getList()
		} finally {
			formLoading.value = false
		}
	}

	// 创建宽带账号(通过用户信息创建)
	const submitCreate2 = async () => {
		// 校验表单
		if (!formRef2) return
		const valid = await formRef2.value.validate()
		if (!valid) return
		formLoading.value = true
		try {
			const data = createFormData as unknown as NetAccountApi.NetAccountCreateVO
			await NetAccountApi.createUser(data)
			message.success(t('common.success'))
			dialogVisibleCreate.value = false
			getList()
		} finally {
			formLoading.value = false
		}
	}

	/** 删除按钮操作 */
	const handleDelete = async (id: number) => {
		try {
			// 删除的二次确认
			await message.delConfirm()
			// 发起删除
			await NetAccountApi.deleteNetAccount(id)
			message.success(t('common.delSuccess'))
			// 刷新列表
			await getList()
		} catch {}
	}

	const subAccountList = ref([])
	const change0pen = async (item: object) => {
		try {
			const data = await NetAccountApi.getNetAccountChildPage(item.id)
			subAccountList.value = data.list || []
			subAccountShow.value = true
		} finally {
		}
	}

	//初始化
	onMounted(() => {
		getNetSysConfigs().then(data => {
			sysConfigList.value = data
		})
		getList()
	})
</script>
<style lang="scss" scoped></style>
